// 完成练习API
import { NextRequest } from 'next/server';
import { SessionDB } from '@/lib/mysql';
import { getCurrentUser, getTokenFromHeader, ApiResponse } from '@/lib/auth';

// 完成练习会话
export async function POST(request: NextRequest) {
  try {
    // 验证用户登录 - 从Authorization header获取token
    const authHeader = request.headers.get('Authorization');
    const token = getTokenFromHeader(authHeader || '');
    const currentUser = getCurrentUser(token || undefined);
    if (!currentUser) {
      return ApiResponse.unauthorized('请先登录');
    }

    // 解析请求体
    const body = await request.json();
    const { sessionId, correctCount, totalTime, score } = body;

    // 验证必填字段
    if (!sessionId || correctCount === undefined || !totalTime || score === undefined) {
      return ApiResponse.error('缺少必填字段');
    }

    // 更新练习会话
    await SessionDB.update(sessionId, correctCount, totalTime, score, true);

    return ApiResponse.success(
      {
        sessionId,
        correctCount,
        totalTime,
        score,
        completed: true,
      },
      '练习完成'
    );
  } catch (error) {
    console.error('完成练习错误:', error);
    return ApiResponse.serverError('完成练习失败');
  }
}
